package geekzpacho.examples.ehcache;

import java.io.Serializable;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

public abstract class AbstractJpaDAO< T extends Serializable > {
	   
	private Class< T > className;
	   
	@PersistenceContext
	EntityManager entityManager;
	   
	public void setClassName( Class< T > classNameToSet ){
		this.className = classNameToSet;
	}
	   
	public T findOne( Integer id ){
	return this.entityManager.find( this.className, id );
	}
   
	@SuppressWarnings("unchecked")
	public List< T > findAll(){
		return this.entityManager.createQuery( "from " + this.className.getName() ).getResultList();
	}
   
	public void save( T entity ) {
		this.entityManager.persist( entity );
	}
   
	public void update( T entity ){
		this.entityManager.merge( entity );
	}
   
	public void delete( T entity ){
		this.entityManager.remove( entity );
	}
	
	public void deleteById( Integer entityId ){
      T entity = this.findOne( entityId );
      
      this.delete( entity );
   }
}